package com.taxshare.jwtfilter;


import cn.hutool.json.JSONObject;
import com.taxshare.jwt.JwtHelper;
import com.taxshare.jwt.JwtInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * JWT解析用户信息过滤器
 *
 * @author jiangye
 * @date 2021/02/19
 */
@Slf4j
@Component
public class JwtFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //Do nothing
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        //获取请求头 用户信息从此token获取
        String token = req.getHeader("refresh-token");
        //如果令牌存在,解析用户信息
        if (StringUtils.isNotBlank(token) && !"null".equals(token)) {
            //进行JWT校验
            try {
                //获取用户信息
                JwtInfo info = JwtHelper.getInfoFromToken(token);
                //用户userId
                req.setAttribute("userId", info.getUserId());
                //用户登陆名称
                req.setAttribute("userLoginName", info.getUserLoginName());
                //用户nickName
                req.setAttribute("userNickName", info.getUserNickName());
                //用户类型
                req.setAttribute("userType", info.getUserType());
                //集团编码
                req.setAttribute("tenantId", info.getTenantId());
                //角色编码
                req.setAttribute("roleId", info.getRoleId());
                //拓展字段
                req.setAttribute("expandField", info.getExpandField());
            } catch (Exception e) {
                HttpServletResponse res = (HttpServletResponse) response;
                //令牌失效
                writeFailure(res);
                return;
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        //Do nothing
    }

    /**
     * 返回错误信息
     */
    private void writeFailure(HttpServletResponse response) throws IOException {
        JSONObject result = new JSONObject();
        result.put("status", 200);
        result.put("code", "TOL_99999");
        result.put("msg", "令牌失效");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(result.toString());
        writer.flush();
        writer.close();
    }

}
